package com.heima.search.canalListerner;

import com.alibaba.fastjson.JSON;
import com.heima.feign.article.AricleFeign;
import com.heima.model.common.article.dto.ArticleDocDto;
import com.heima.model.common.article.pojo.ApArticleConfig;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.search.pojo.ArticleDoc;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.io.IOException;

@Component
@Slf4j
@CanalTable("ap_article_config")
public class ApArticleConfigHandler implements EntryHandler<ApArticleConfig> {
    @Autowired
    private AricleFeign aricleFeign;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public void insert(ApArticleConfig apArticleConfig) {
      //有新文案发布
        //发布文章同步到es
        try {
            Long articleId = apArticleConfig.getArticleId();
            ResponseResult<ArticleDocDto> responseResult = aricleFeign.findById(articleId);
            addA(responseResult);
        } catch (IOException e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }

    }

    @SneakyThrows
    @Override
    public void update(ApArticleConfig before, ApArticleConfig after) {
    //文章被进行了上下架
        //删除es 添加es
        if (after.getIsDown()){
            //下架 。删除es
            DeleteRequest deleteRequest = new DeleteRequest("app_info_article",String.valueOf(after.getArticleId()));
            restHighLevelClient.delete(deleteRequest,RequestOptions.DEFAULT);
        }else {
            //上架 。添加es
            ResponseResult<ArticleDocDto> responseResult = aricleFeign.findById(after.getArticleId());
            addA(responseResult);
        }
    }
    private void addA(ResponseResult<ArticleDocDto> responseResult) throws IOException {
        if (responseResult.getCode()== AppHttpCodeEnum.SUCCESS.getCode()){
            //讲文章同步到es
            ArticleDocDto docDto = responseResult.getData();
            ArticleDoc doc = new ArticleDoc(docDto);
            IndexRequest indexRequest = new IndexRequest("app_info_article");
            indexRequest.id(doc.getId());
            indexRequest.source(JSON.toJSONString(doc), XContentType.JSON);
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        }
    }
}
